package week07.necessary.config;

import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import week07.necessary.enums.DatasourceEnums;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


@Component
@Primary
public class DynamicDataSource extends AbstractRoutingDataSource {
    private final DatasourceContextHolder contextHolder;

    public DynamicDataSource(DatasourceContextHolder contextHolder, Map<String, DataSource> dataSourceMap) {
        this.contextHolder = contextHolder;

        Map<Object, Object> tds = new HashMap<>();
        dataSourceMap.forEach((k, v) -> tds.put(DatasourceEnums.getInstance(k), v));
        this.setTargetDataSources(tds);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return contextHolder.getContext();
    }
}
